<?php

namespace frontend\controllers;

use Yii;
use frontend\models\User;
use frontend\models\Product;
use frontend\models\Order;
use frontend\models\ProductPrice;
use frontend\models\Coupon;
use frontend\models\UserCoupon;
use frontend\models\DataAll;

class OrderController extends \frontend\components\Controller
{
    public function beforeAction($action)
    {
        if (user()->isGuest) {
            $this->redirect(['site/login']);
            return false;
            // $wx = session('wechat_userinfo');
            // if (!empty($wx)) {
            //     $user = User::find()->where(['open_id' => $wx['openid']])->one();
            //     $user->login(false);
            // } else {
            //     $code = get('code');
            //     if (empty($code)) {
            //         $this->redirect(['/wechart.php']);
            //         return false;
            //     } else {
            //         User::registerUser($code);
            //     }
            // }
        }
        if (!parent::beforeAction($action)) {
            return false;
        } else {
            return true;
        }
    }

    //下单操作
    public function actionIndex()
    {
        $this->view->title = '下单';
        $pid = req('pid');
        if (user()->isGuest) {
            return $this->redirect(['site/login']);
        }
        $product = Product::find()->andWhere(['id' => $pid])->with('dataAll')->one();
        $productPrice = ProductPrice::getSetProductPrice($product->id);
        if (!isset($productPrice)) {
            return $this->redirect(['site/wrong']);
        }
        //体验卷
        $couponType = UserCoupon::getNumberType($pid);
        return $this->render('index', compact('product', 'productPrice', 'couponType'));
    }

    //持仓列表
    public function actionPosition()
    {
        $this->view->title = '持仓';

        $model = new Order();
        $query = $model->positionQuery();
        $data = $query->paginate(5);
        $pageCount = $query->totalCount / 5;
        // test($pageCount);
        if (!is_int($pageCount)) {
            $pageCount = (int)$pageCount + 1;
        }
        if (get()) {
            return success($this->renderPartial('_positionList', compact('data')), $pageCount);
        }
        //当前可用产品
        $productArr = Product::getProductArray();
        return $this->render('position', compact('data', 'pageCount', 'model', 'productArr'));
    }

    //平仓
    public function actionSellPosition($id)
    {
        $this->view->title = '平仓';
        if (user()->isGuest) {
            return $this->redirect(['site/login']);
        }
        $order = Order::find()->where(['order_state' => Order::ORDER_POSITION, 'user_id' => u()->id, 'id' => $id])->with('product')->one();
        if (empty($order)) {
            return $this->redirect(['site/index']);
        }
        return $this->render('sellPosition', compact('order'));
    }

    /**
     * 更新所有持仓单数据ajax请求
     * @access public
     * @return json
     */
    public function actionAjaxUpdateOrder()
    {
        $orders = Order::find()->where(['order_state' => Order::ORDER_POSITION, 'user_id' => u()->id])->all();
        $data = [];
        foreach ($orders as $order) {
            $data[$order->id] = Order::userWinOrder($order);
        }
        return success($data);
    }

    /**
     * 更新一条持仓单数据ajax请求
     * @access public
     * @return json
     */
    public function actionAjaxUpdateOrderOne()
    {
        $data = Order::getUserOrderData(post('id'));
        // test($data);
        return success($data);
    }

    /**
     * 保存订单
     * @access public
     * @return json
     */
    public function actionAjaxSaveOrder()
    {
        $data = post();
        $productPrice = ProductPrice::findModel($data['price_id']);
        // test($data['deposit']);
        if (empty($productPrice)) {
            return error('非法参数！');
        }
        // if ($data['deposit'] > $productPrice->deposit) {
        //     return error('单笔下单已超过最大金额！');
        // }
        // test($data['deposit']);
        if(!is_numeric($data['deposit'])) return error('请选择金额');
        //判断此期货是否在交易时间内
        if (!Product::isTradeTime($productPrice->product_id)) {
            return error('非买入时间，无法委托买入！');
        }
        $order = Order::find()->where(['order_state' => Order::ORDER_POSITION, 'user_id' => u()->id, 'product_id' => $productPrice->product_id])->orderBy('created_at DESC')->one();
        $time = $order?time() - strtotime($order->created_at):BUY_ORDER_TIME + 1;  
        if ($time <= BUY_ORDER_TIME) {
            return error('下单后'.BUY_ORDER_TIME.'秒之内不能再次下单！');
        }
        //订单处理
        $res = Order::saveOrder($data, $productPrice);
        if ($res['code'] == 1) {
            return success($res['info']);
        } else {
            return error($res['info']);
        }
    }

    /**
     * 平仓订单ajax请求
     * @access public
     * @return json
     */
    public function actionSo()
    {
        $bool = Order::sellOrder(10);
        if ($bool) {
            self::success('平仓成功！');
        } else {
            self::error('订单数据不存在！');
        }
    }
}
